package com.example.travelsn.homepage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.travelsn.R;
import com.example.travelsn.db.DBManager;
import com.example.travelsn.db.Feedback;
import com.example.travelsn.db.Good;
import com.luluteam.itestlib.apm.test.tool.FragmentProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class SellerFragment extends Fragment {
    //布局控件
    private Button bFeedback;
    private Button bUpstore;
    private Button bAddgood;
    private EditText etFeedback;
    private ListView lvSeller;
    //ListView相关
    private List<Map<String, Object>> listItem;
    private DBManager dbManager;
    List<Good> goodsList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentProxy.callonCreate(this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_seller, container, false);
    }
    @Override
    public void  onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initEvent();
        initListView();
        bFeedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //信息反馈
                String sFeedback = etFeedback.getText().toString();
                if(!sFeedback.equals("") && sFeedback != null){
                    System.out.println(sFeedback);
                    Feedback feedback = new Feedback();
                    feedback.setContent(sFeedback);
                    dbManager.addFeed(feedback);
                    Toast.makeText(getActivity(),"反馈成功",Toast.LENGTH_SHORT).show();
                    etFeedback.setText("");
                    //关闭软键盘
                    InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
                    if ( imm.isActive( ) ) {
                        imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 );
                    }
                }
                else Toast.makeText(getActivity(),"请输入反馈内容",Toast.LENGTH_SHORT).show();
            }
        });
        bUpstore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upStore();
            }
        });
        bAddgood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addGoods();
            }
        });
        lvSeller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 将点击的item里面的字弹出来
                View up_view= LayoutInflater.from(getActivity()).inflate(R.layout.update_good, null);
                final HashMap<String,String> map=(HashMap<String,String>)lvSeller.getItemAtPosition(position);
                final EditText upPrice = up_view.findViewById(R.id.et_upprice);
                Button update =  up_view.findViewById(R.id.b_up_price);
                AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
                final Dialog upDialog= builder.create();
                upDialog.show();
                upDialog.getWindow().setContentView(up_view);
                //使editext可以唤起软键盘
                upDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                update.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(!upPrice.getText().toString().equals("")){
                            dbManager.upGoods(map.get("goodsname"),map.get("sellername"),Float.parseFloat(upPrice.getText().toString()));
                            Log.d("Reminder","更新价格成功");
                            initListView();
                            upDialog.dismiss();
                        }
                    }
                });
            }
        });
        lvSeller.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(getContext()).setTitle("确认删除吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“确认”后的操作
                                HashMap<String,String> map=(HashMap<String,String>)lvSeller.getItemAtPosition(position);
                                dbManager.deleteGood(map.get("goodsname"),map.get("sellername"));
                                initListView();
                            }
                        })
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
                return true;
            }
        });

    }
    @Override
    public void onResume() {
        super.onResume();
        FragmentProxy.callonResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        FragmentProxy.callonPause(this);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        lvSeller.setAdapter(null);
    }

    private void initEvent(){
        bFeedback = (Button)getActivity().findViewById(R.id.b_sellfeed);
        bUpstore= (Button)getActivity().findViewById(R.id.b_upstore);
        bAddgood = (Button)getActivity().findViewById(R.id.b_addgood);
        etFeedback = (EditText)getActivity().findViewById(R.id.et_sellfeed);
        lvSeller = (ListView)getActivity().findViewById(R.id.lv_goods);
        listItem = new ArrayList<Map<String, Object>>();
        dbManager = new DBManager(getContext());
    }
    private void initListView(){
        System.out.println("正在运行initListView");
        lvSeller.setAdapter(null);
        listItem.removeAll(listItem);
        goodsList = dbManager.getGoods(getSellerName());
        for (int i = 0; i < goodsList.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("goodsname", goodsList.get(i).getGoodsName());
            map.put("goodstype", goodsList.get(i).getGoodsType());
            map.put("unitprice", goodsList.get(i).getUnitPrice());
            map.put("sellername", goodsList.get(i).getSellerName());
            if(!map.isEmpty() && map !=null){
                listItem.add(map);
            }else System.out.println("map为空");

        }
        if(listItem!=null && !listItem.isEmpty()){
            SimpleAdapter adapter = new SimpleAdapter(getActivity()
                    , listItem
                    , R.layout.listgoods_item
                    , new String[]{"goodsname", "goodstype","unitprice","sellername"}
                    , new int[]{R.id.tv_goodsname, R.id.tv_goodstype,R.id.tv_unitprice,R.id.tv_sellername});
            lvSeller.setAdapter(adapter);
        }
    }
    private void upStore(){
        AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
        View view= LayoutInflater.from(getActivity()).inflate(R.layout.create_sellerdialog, null);
        final EditText latitude =view.findViewById(R.id.editText_j);
        final EditText longitude =view.findViewById(R.id.editText_w);
        Button submit =  view.findViewById(R.id.dialog_button);
        final Dialog dialog= builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        //使editext可以唤起软键盘
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!latitude.getText().toString().equals("") && !longitude.getText().toString().equals("")){
                    Float dbLatitude = Float.parseFloat(latitude.getText().toString());
                    Float dbLongitude = Float.parseFloat(longitude.getText().toString());
                    String sellername = getSellerName();
                    dbManager.updataSeller(dbLatitude,dbLongitude,sellername);
                    System.out.println("已提交");
                    dialog.dismiss();
                }
                else
                    new AlertDialog.Builder(getContext()).setTitle("输入有误")
                            .setMessage("请输入完整信息")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
            }
        });
    }
    private void addGoods(){
        AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
        View view= LayoutInflater.from(getActivity()).inflate(R.layout.add_goods, null);
        final EditText goodname =view.findViewById(R.id.et_goodname);
        final EditText unitprice =view.findViewById(R.id.et_price);
        final EditText goodtype = view.findViewById(R.id.et_goodtype);
        Button addGood =  view.findViewById(R.id.b_addgood);
        final Dialog dialog= builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        //使editext可以唤起软键盘
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        addGood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(goodname.getText().toString().equals("") || unitprice.getText().toString().equals("")
                    || goodtype.getText().toString().equals("")){
                    new AlertDialog.Builder(getContext()).setTitle("输入有误")
                            .setMessage("请输入完整信息")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }else{
                    Good good = new Good();
                    good.setGoodsName(goodname.getText().toString());
                    good.setUnitPrice(Float.parseFloat(unitprice.getText().toString()));
                    good.setGoodsType(goodtype.getText().toString());
                    good.setSellerName(getSellerName());
                    dbManager.addGoods(good);
                    System.out.println("添加商品成功");
                    initListView();
                    dialog.dismiss();
                }
            }
        });
    }
    private String  getSellerName(){
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("name","not logged");
    }
}
